<html>
<head>
<script type="application/javascript;version=1.8">
function TestData(aOpts) {
  for (var opt in aOpts) {
    if (aOpts.hasOwnProperty(opt)) {
      this[opt] = aOpts[opt];
    }
  }
}

TestData.prototype = {
  getObj: function() {
    if (!this.obj) {
      return null;
    }

    // only one of the 2 should be set
    if ((this.idl && this.webidl) ||
        (!this.idl && !this.webidl)) {
      return null;
    }

    // split on . to allow nested props
    var props = this.obj.split(".");
    var obj = window.navigator;

    for (var i = 0; i < props.length && obj !== undefined; i++) {
      obj = obj[props[i]];
    }

    if ((this.webidl && obj instanceof window[this.webidl]) ||
        (this.idl && obj instanceof SpecialPowers.Ci[this.idl])) {
      return obj;
    } else {
      return null;
    }
  },

  // default verifier
  verifier: function(success, failure) {
    try {
      if (this.getObj()) {
        success(this.perm);
      } else {
        failure("Did not receive proper object");
      }
    } catch (e) {
      failure("Received exception!: " + e);
    }
  },
}

function receiveMessage(e) {
  var src = e.source;
  var step = e.data.step;
  var id = e.data.id;
  var data = new TestData(e.data.testdata);
  var success, failure;

  function reply(res, msg) {
    window.removeEventListener("message", receiveMessage, false);
    src.postMessage({result: res, msg: msg,
                     id: id}, "*");
  }

  function _success(msg) {
    reply(true, msg);
  }

  function _failure(msg) {
    reply(false, msg);
  }

  // flip success and failure around for precheck
  if (step == 0) {
    success = _failure;
    failure = _success;
  } else {
    success = _success;
    failure = _failure;
  }

  if (data.verifier instanceof Function) {
    data.verifier(success, failure);
  } else {
    // import toSource() function to global
    eval(data.verifier);
    verifier.bind(data, success, failure)();
  }
}

window.addEventListener("message", receiveMessage, false);
</script>
</head>
<body>
<div id="content" style="display: none"></div>
</body>
</html>
